package com.sskj.fabi.ui.fragment;


import android.support.design.widget.BottomSheetDialog;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.fabi.R;
import com.sskj.fabi.R2;
import com.sskj.fabi.bean.BuySellBean;
import com.sskj.fabi.bean.FilterBean;
import com.sskj.fabi.bean.OrderDetailBean;
import com.sskj.fabi.bean.PayWayItem;
import com.sskj.fabi.component.DaggerUserDataComponent;
import com.sskj.fabi.presenter.BuySellFragmentPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.enums.PayTypeEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.mvchelper.ModelRx2DataSource;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.CoinUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.lib.util.StringUtil;
import com.sskj.lib.util.TipUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.FABI_FRAGMENT_BUY_SELL)
public class BuySellFragment extends BaseFragment<BuySellFragmentPresenter> {
    @Autowired
    boolean isBuy;  // true 购买大厅  false 出售大厅
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;

    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private SlimAdapter slimAdapter;
    private int curPos;
    private BottomSheetDialog orderSheet;
    private MVCCoolHelper<List<BuySellBean>> mvcHelper;
    private List<PayWayItem> listPay;  // 当前用户支付方式
    private String pType;
    private String minMoney;
    private BuySellBean dataItem;

    @Override
    protected int getLayoutId() {
        return R.layout.fabi_fragment_buy_sell;
    }

    @Override
    public BuySellFragmentPresenter getPresenter() {
        return new BuySellFragmentPresenter();
    }

    @Override
    protected void initView() {
        ARouter.getInstance().inject(this);
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
                mPresenter.requsetPayWayList();
            } else {
                userData = null;
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setFirstDraw(false)
                .setLeftPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setRightPadding((int) RudenessScreenHelper.pt2px(App.INSTANCE, 30))
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.fabiDivider))
        );
        // 剩余数量
        slimAdapter = SlimAdapter.create().register(R.layout.fabi_recy_item_buy_sell, new SlimInjector<BuySellBean>() {
            @Override
            public void onInject(BuySellBean data, IViewInjector injector, List payloads) {
                injector.text(R.id.tvName, data.getUsername())
                        .text(R.id.tvDealNum, "成交" + " " + CoinUtil.keepUSDT(data.getDealsNum()))
                        .text(R.id.tvPercent, "成交率" + " " + ((data.getComplete() + data.getCancle()) == 0 ? 0 : NumberUtil.keepMax2(100 * data.getComplete() / (data.getComplete() + data.getCancle()))) + "%")
                        .text(R.id.tv_num, "数量" + "  " + data.getTransNum() + " USDT")  // 剩余数量
                        .text(R.id.tvLimitMoney, "限额" + "  " + data.getMinPrice() + "-" + data.getMaxPrice() + " CNY")
                        .text(R.id.tv_china_money, "¥" + data.getPrice())
                        .text(R.id.tvPhoto, StringUtil.getFirstName(data.getUsername()))
                        .text(R.id.btSale, isBuy ? "去购买" : "去出售")
                        .visibility(R.id.iv_wechat, data.getPayType().contains("1") ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_bank, data.getPayType().contains("3") ? View.VISIBLE : View.GONE)
                        .visibility(R.id.iv_alipay, data.getPayType().contains("2") ? View.VISIBLE : View.GONE)
                        .background(R.id.btSale, isBuy ? R.drawable.fabi_solid_ff5_bg : R.drawable.fabi_solid_03c_bg)
                ;
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
        ModelRx2DataSource<BuySellBean> dataSource = new ModelRx2DataSource<>((ModelRx2DataSource.OnLoadSource<BuySellBean>)
                page -> mPresenter.getData(page + "", 20 + "", isBuy, pType, minMoney), 20);
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapter);

        mvcHelper.refresh();
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, i, view) -> {
                    curPos = i;
                    trade();
                });
    }

    @Override
    protected void initData() {
        LiveDataBus.get().with(RxBusCode.CHANGE_FABI_MARKET_FILTER, FilterBean.class)
                .observe(this, filterBean -> {
                    pType = filterBean.getpType();
                    minMoney = filterBean.getMinMoney();
                    mvcHelper.refresh();
                });
        LiveDataBus.get().with(RxBusCode.PUBLISH_SUCCESS)
                .observe(this,o -> refresh());
    }

    private void trade() {
        if (!AppCircleCheckUtil.checkLogin(getActivity(), userData)) {
            return;
        }
        dataItem = (BuySellBean) slimAdapter.getDataItem(curPos);
        if (SPUtil.get(SPConfig.ID, "").equals(dataItem.getStockUserId())) {
            ToastUtil.showShort("禁止向自己发起交易");
            return;
        }
        if (isBuy) {
            if (!AppCircleCheckUtil.checkAuth(getActivity(), userData)) {
                return;
            }
        } else {
            if (!AppCircleCheckUtil.checkHighAuth(getActivity(), userData)) {
                return;
            }
            if (!AppCircleCheckUtil.checkTradePwd(getActivity(), userData)) {  // 资金密码
                return;
            }
            if (!checkPayMatch(isBuy, listPay, dataItem)) {
                return;
            }
        }
        if (isBuy) {
            tryTrade(0);
        } else {
            mPresenter.getPositionNum();
        }


    }



    public void orderSuccess(OrderDetailBean orderDetailBean) {
        if (orderSheet != null && orderSheet.isShowing()) {
            orderSheet.dismiss();
        }
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
        ARouter.getInstance().build(RConfig.FABI_ORDER_RECORD_DETAIL)
                .withString(Constans.ORDER_NUM, orderDetailBean.getDealEntrustNo())
                .withBoolean(Constans.IS_BUYER, isBuy)
                .navigation();

    }

    // 记录用户支付方式
    public void updateUi(List<PayWayItem> listPay) {
        this.listPay = listPay;
    }

    @Override
    public void onResume() {

        super.onResume();
        if (mPresenter != null && userData != null) {
            mPresenter.requsetPayWayList();
        }
    }

    //检测用户支付方式是否匹配的上买家支付方式
    public boolean checkPayMatch(boolean isBuy, List<PayWayItem> payList, BuySellBean bean) {
        StringBuffer sbText = new StringBuffer();
        if (payList == null) {
            ToastUtil.showShort("数据获取失败，请刷新页面");
            mPresenter.requsetPayWayList();

            return false;
        }
        if (bean.getPayType().contains(PayTypeEnum.ALIPAY.getType())) {  // 买家有支付宝
            sbText.append("、" + "支付宝");
            for (int i = 0; i < payList.size(); i++) {
                if (payList.get(i).getPayType() == 2 && !payList.get(i).isStatus()) {  //卖家有支付宝
                    return true;
                }
            }
        }
        if (bean.getPayType().contains(PayTypeEnum.WX.getType())) { // 买家有微信
            sbText.append("、" + "微信");
            for (int i = 0; i < payList.size(); i++) {
                if (payList.get(i).getPayType() == 1 && !payList.get(i).isStatus()) {  //卖家有微信
                    return true;
                }
            }
        }
        if (bean.getPayType().contains(PayTypeEnum.BANK.getType())) { // 买家有银行卡
            sbText.append("、" + "银行卡");
            for (int i = 0; i < payList.size(); i++) {
                if (payList.get(i).getPayType() == 3 && !payList.get(i).isStatus()) {  //卖家有微信
                    return true;
                }
            }
        }
        if (!isBuy) {
            TipUtil.getSureTip(getActivity(), "提醒", String.format("买家仅支持通过%s向您付款,您需要添加并激活相应收款方式", sbText.substring(1)), "添加", () -> {
                ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
            });
        } else {
            TipUtil.getSureTip(getActivity(), "提醒", String.format("卖家仅支持通过%s由您付款,您需要添加并激活相应付款方式", sbText.substring(1)), "添加", () -> {
                ARouter.getInstance().build(RConfig.MINE_SECURITY_CENTER).navigation();
            });
        }
        return false;
    }

    public void refresh() {
        mvcHelper.refresh();
    }

    public void tryTrade(Integer data) {
        if (data > 0) {
            ToastUtil.showShort("您有持仓单，不能交易");
            return;
        }
        ArrayList<PayTypeEnum> payTypeEnums = new ArrayList<>();
        if (!isBuy) {
            for (int i = 0; i < listPay.size(); i++) {
                if (dataItem.getPayType().contains(listPay.get(i).getPayType() + "")&&!listPay.get(i).isStatus()) {
                    payTypeEnums.add(PayTypeEnum.getByType(listPay.get(i).getPayType() + ""));
                }
            }
        } else {
            String[] split = dataItem.getPayType().split(",");
            for (int i = 0; i < split.length; i++) {
                payTypeEnums.add(PayTypeEnum.getByType(split[i]));
            }
        }

        ARouter.getInstance()
                .build(RConfig.FABI_ORDER)
                .withBoolean(Constans.IS_BUY, isBuy)
                .withSerializable(Constans.DATA, dataItem)
                .withSerializable(Constans.PAY_TYPE, payTypeEnums)
                .navigation();
    }
}

